package cn.nami.web.frontpage.jdo;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import cn.nami.web.db.util.PMF;
import cn.nami.web.frontpage.entity.Visitor;
import cn.nami.web.util.StringUtil;

public class VisitorJdo
{
	private VisitorJdo(){};
	
	private static final Logger logger = Logger.getLogger(VisitorJdo.class.getName());

	/**
	 * persistent a visitor to data store.
	 */
	public static void save(Visitor visitor)
	{
		logger.info("Persistent visitor begin...");
		if(visitor == null)
		{
			logger.warning("Persistent visitor failure : the visitor is null.");
			return;
		}
		PersistenceManager pm = null;
		try
		{
			pm = PMF.get().getPersistenceManager();
			pm.makePersistent(visitor);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.severe("Persistent a visitor error, visitor : " + visitor + e.getMessage());
		}
		finally
		{
			PMF.close(pm);
			logger.info("Persistent visitor end...");
		}
	}
	
	/**
	 * list all visitors from db
	 */
	@SuppressWarnings("unchecked")
	public static List<Visitor> listAllVisitors(String order)
	{
		logger.info("List all visitors begin...");
		order = (StringUtil.isEmpty(order) ? "id" : order);
		List<Visitor> visitorList = null;
		String sql = "select from " + Visitor.class.getName() + " order by " + order;
		PersistenceManager pm = null;
		try
		{
			pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(sql);
			visitorList = (List<Visitor>)query.execute();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.severe("list all visitor error : " + e.getMessage());
		}
		finally
		{
			PMF.close(pm);
			logger.info("List all visitors end...");
		}
		return visitorList;
	}

	/**
	 * delete a visitor
	 */
	public static void deleteById(Integer id)
	{
		logger.info("delete visitor begin...");
		PersistenceManager pm = null;
		try
		{
			pm = PMF.get().getPersistenceManager();
			Visitor visitor = pm.getObjectById(Visitor.class, id);
			pm.deletePersistent(visitor);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.severe("delete visitor error : " + e.getMessage());
		}
		finally
		{
			PMF.close(pm);
			logger.info("delete visitor end...");
		}
	}
}